/**
 * Created by 1 on 2016/12/30.
 */
(function(){
    "use strict";
    var shapeLayouts=[
        [[0,1,0],[1,1,1]],
        [[1,1,1,1]],
        [[1,1],[1,1]],
        [[0,1],[1,1],[1,0]],
        [[1,0],[1,1],[0,1]],
        [[1,0,1],[1,1,1]],
        [[0,1],[1,1]],
        [[1,1],[1,0],[1,0]],
        [[1,1],[0,1],[0,1]]
    ];
    var random=function(minValue,maxValue){
        return minValue+Math.floor(Math.random()*maxValue);
    };
    var styleCount=7;
    function Shape(){
        this.blockType=random(1,styleCount);
        this.x=0;
        this.y=0;
        this.block=new Block(this.blockType);
        this.layout=shapeLayouts[random(0,shapeLayouts.length)]; //实现组合变换
    }
    Shape.prototype={
        constructor:Shape,
        draw:function(context,size){
            for(var i=0;i<this.layout.length;i++){
                for(var j=0;j<this.layout[i].length;j++){
                    if(this.layout[i][j]){
                        this.block.draw(context,i+this.x,j+this.y,undefined,size);
                    }
                }
            }
        },
        //翻转算法
        rotate: function () {
            this.newlayout = [];
            for (var y = 0; y < this.layout[0].length; y++) {
                this.newlayout[y] = [];
                for (var x = 0; x < this.layout.length; x++) {
                    this.newlayout[y][x] = this.layout[this.layout.length - 1 - x][y];
                }
            }
            this.layout = this.newlayout;
            this._setLayout();
        },
        //将翻转越界的方块重新归位
        _setLayout:function(){
            if(this.x<0){
                this.x=0;
            }else if((this.x+this.layout.length)>window.TetrisConfig.cols){
                this.x=window.TetrisConfig.cols-this.layout.length;
            }else if(this.y<0){
                this.y=0;
            }else if(this.y+this.layout[0].length>window.TetrisConfig.rows){
                this.y=window.TetrisConfig.rows-this.layout[0].length;
            }
        },
        _setMaxCols:function(){
            return this.layout.length;
        },
        _setMaxRows:function(){
            var max=0;
            for(var i=0;i<this.layout.length;i++){
                max=Math.max(max,this.layout[i].length);
            }
            return max;
        },
        setPosition: function (cols,rows) {
                this.x=Math.floor((cols-this._setMaxCols())/2);
                this.y=Math.floor((rows-this._setMaxRows())/2);
        }
    };
    window.Shape=Shape;
})();